import React from 'react'
import {connect} from 'mirrorx'
import {Form} from 'antd'

import MidNav from 'component/MidNav'
import StepOne from './step-one'
import StepTwo from './step-two'
import StepThree from './step-three'

class App extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      windowHeight: '1000px',
      step: 1,
      fileList: [],
      previewVisible: false,
      previewImage: '',
      countryDatasource: [],
      submitData: {},
      confirmDirty: false,
      businessLicenseUsed: false,
      fileName: ''
    }
    this.next = this.next.bind(this)
    this.backToPrev = this.backToPrev.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.handleConfirmBlur = this.handleConfirmBlur.bind(this)
  }
  componentDidMount () {
    this.setState({
      windowHeight: T.getScreenHeight() - 36
    })
    this.requestCountryList()
    this.requestVerifyInfo()
  }

  componentWillReceiveProps (nextprops) {
    if (nextprops.userInfo) {
      let userInfo = nextprops.userInfo
      if (userInfo.name) {
        this.setState({
          userName: userInfo.name || ''
        })
      }
    }
  }

  getuserId () {
    let {userInfo} = this.props
    let userId = ''
    if (userInfo && userInfo.userId) {
      userId = userInfo.userId
    }
    return userId
  }

  next () {
    const step = this.state.step
    if (step > 2) {
      return
    }
    this.setState({
      step: step + 1
    })
  }

  requestCountryList () { // 获取国家列表
    T.ajax({
      url: 'api/uc/channel/allCountries',
      data: {}
    }).then((res) => {
      if (res.success && res.data) {
        this.setState({
          countryDatasource: res.data
        })
      }
    })
  }

  requestVerifyInfo () { // 获取上次认证失败的信息
    T.ajax({
      url: 'api/uc/channel/getMyCompanyInfo'
    }).then((res) => {
      if (res.success && res.data) {
        this.setState({
          submitData: res.data
        })
      } else {
        this.getInfoFromSession()
      }
    })
  }

  getInfoFromSession () {
    let submitData = T.sessionStorage.get('submitData' + this.getuserId())
    if (submitData) {
      submitData = JSON.parse(submitData)
      submitData.licenseFile = null
      this.setState({
        submitData
      })
    }
  }

  handleSubmit (e) {
    e.preventDefault()
    const {step, businessLicenseUsed} = this.state
    this.props.form.validateFields((err, values) => {
      if (!err) {
        let submitData = this.state.submitData
        Object.assign(submitData, values)
        this.setState({
          submitData: submitData
        })
        T.sessionStorage.set('submitData' + this.getuserId(), submitData) // 放缓存
        if (step <= 1) {
          this.next()
        }
        if (step >= 2) {
          if (!submitData.licenseFile && !submitData.licenseFileCode) {
            T.showError('Please upload business license')
            return
          }
          if (!values.agree) {
            T.showError('Please check the terms')
            return
          }
          if (businessLicenseUsed) {
            T.showError('The bussiness license has been used before')
            return
          }
          this.requestVerification(submitData)
        }
      }
    })
  }

  requestVerification (values) {
    const {countryDatasource} = this.state
    const obj = T.getAttrObject(countryDatasource, 'iso3', values.country)[0] || {}
    const areaCode = (obj && obj.phonecode) || '' // 处理电话区号
    values.areaCode = areaCode
    delete values.agree
    delete values.verificationState
    delete values.channelCompanyId
    if (values.licenseFileCode) {
      delete values.licenseFile
    }
    var formData = new FormData()
    for (var key in values) {
      if (key === 'licenseFile' && values[key].file) {
        values[key] = values[key].file
      }
      formData.append(key, values[key])
    }
    T.ajax({
      url: '/proxy/api/uc/channel/applyCertification',
      data: formData,
      loading: true
    }).then((res) => {
      if (res.success) {
        this.setState({
          step: 3
        })
      }
    })
  }

  backToPrev (e) {
    const step = this.state.step
    if (step <= 1) {
      return
    }
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        let submitData = this.state.submitData
        Object.assign(submitData, values)
        this.setState({
          submitData: submitData
        })
        T.sessionStorage.set('submitData' + this.getuserId(), submitData) // 放缓存
      }
    })
    this.setState({
      step: step - 1
    })
  }

  renderFile (file) {
    this.setState({
      fileName: file.name
    })
  }

  getFileProps (callback) { // 允许的文件格式为doc,docx,pdf,png,jpg
    return {
      action: '/',
      accept: 'image/jpeg,application/pdf,application/msword,image/png,application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      beforeUpload: (file) => {
        let fileSize = file.size / (1024 * 1024)
        if (fileSize > 10) {
          T.showError('The file size should no more than 10M')
          return false
        }
        callback && callback(file)
        return false
      },
      fileList: []
    }
  }

  getFile (file) {
    this.props.form.setFieldsValue({
      licenseFile: file
    })
    if (this.state.submitData.licenseFileCode) {
      delete this.state.submitData.licenseFileCode
      this.setState({
        submitData: this.state.submitData
      })
    }
  }

  checkBussinessLicense (value) {
    T.ajax({
      url: '/api/uc/channel/businessLicenseApplied',
      data: {businessLicense: value}
    }).then((res) => {
      if (res.success && res.data) {
        return true
      }
    })
  }

  handleConfirmBlur (e) {
    const value = e.target.value
    this.setState({ confirmDirty: this.state.confirmDirty || !!value })
    if (this.checkBussinessLicense(value)) {
      T.showError('The bussiness license has been used before')
      this.setState({
        businessLicenseUsed: true
      })
    } else {
      this.setState({
        businessLicenseUsed: false
      })
    }
  }

  render () {
    const {windowHeight, step, fileList, countryDatasource, submitData, fileName, userName} = this.state
    const {getFieldDecorator} = this.props.form
    const fileProps1 = this.getFileProps((file) => {
      this.getFile(file)
      this.renderFile(file)
    })
    return (
      <div>
        <div className='verification' style={{minHeight: windowHeight}}>
          <MidNav title='Verification' />

          <div className='wrap'>
            <div className='innerBox'>
              <div className='tabs'>
                <ul>
                  <li className='fl'>
                    <div className='circle circleActive'>
                      <i className='iconfont icon-basicinformation fcw f14' />
                    </div>
                    <span className={step > 1 ? 'f14 tac ml10 diy_color' : 'f14 fc6 tac ml10'}>Basic Information</span>
                    <div className={step > 1 ? 'dotWrap dotWrapr dotActive' : 'dotWrap dotWrapr'}>
                      <i className='iconfont icon-daoxiang f14' /> <i className='iconfont icon-daoxiang f14' />
                    </div>
                  </li>
                  <li className='fl'>
                    <div className={step > 1 ? 'circle circleActive' : 'circle'}>
                      <i className='iconfont icon-businesslicense fcw f14' />
                    </div>
                    <span className={step > 2 ? 'f14 tac ml10 diy_color' : 'f14 fc6 tac ml10'}>Business License</span>
                    <div className={step > 1 ? 'dotWrap dotWrapl dotActive' : 'dotWrap dotWrapl'}>
                      <i className='iconfont icon-daoxiang f14' />
                    </div>
                    <div className={step > 2 ? 'dotWrap dotWrapr dotActive' : 'dotWrap dotWrapr'}>
                      <i className='iconfont icon-daoxiang f14' /> <i className='iconfont icon-daoxiang f14' />
                    </div>
                  </li>
                  <li className='fl'>
                    <div className={step > 2 ? 'circle circleActive' : 'circle'}>
                      <i className='iconfont icon-sucessfully fcw f14' />
                    </div>
                    <span className={step > 2 ? 'f14 tac ml10 diy_color' : 'f14 fc6 tac ml10'}>Submit Sucessfully</span>
                    <div className={step > 2 ? 'dotWrap dotWrapl dotActive' : 'dotWrap dotWrapl'}>
                      <i className='iconfont icon-daoxiang f14' />
                    </div>
                  </li>
                </ul>
              </div>
              <Form onSubmit={this.handleSubmit} className='step-one pt30'>
                {step === 1 &&
                <StepOne
                  next={this.next}
                  getFieldDecorator={getFieldDecorator}
                  compareVerifyCode={this.compareVerifyCode}
                  countryDatasource={countryDatasource}
                  submitData={submitData}
                  userName={userName}
                />
                }
                {step === 2 &&
                <StepTwo
                  next={this.next}
                  getFieldDecorator={getFieldDecorator}
                  backToPrev={this.backToPrev}
                  fileList={fileList}
                  submitData={submitData}
                  getFileProps={this.getFileProps}
                  fileProps1={fileProps1}
                  fileName={fileName}
                  handleConfirmBlur={this.handleConfirmBlur}
                />
                }
              </Form>
              {step === 3 &&
              <StepThree />
              }
            </div>
          </div>
        </div>
      </div>

    )
  }
}

const FormWrapper = Form.create()(App)

export default connect(state => {
  return state.mainModel
})(FormWrapper)
